<template>
  <div class="chat-room">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <h2>{{ title }}</h2>
      <div class="chat-id">会话ID: {{ chatId }}</div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.type]"
      >
        <div class="message-content">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
        </div>
      </div>

      <!-- 正在输入指示器 -->
      <div v-if="isTyping" class="message ai typing">
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <textarea
          v-model="inputMessage"
          @keydown.enter.prevent="handleSend"
          @input="adjustTextareaHeight"
          ref="messageInput"
          placeholder="请输入您的消息..."
          :disabled="isLoading"
          rows="1"
        ></textarea>
        <button
          @click="handleSend"
          :disabled="!inputMessage.trim() || isLoading"
          class="send-button"
        >
          {{ isLoading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ChatRoom',
  props: {
    title: {
      type: String,
      default: '聊天室'
    },
    chatId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      messages: [],
      inputMessage: '',
      isLoading: false,
      isTyping: false
    }
  },
  methods: {
    /**
     * 发送消息
     */
    handleSend() {
      if (!this.inputMessage.trim() || this.isLoading) {
        return
      }

      const message = this.inputMessage.trim()

      this.addMessage('user', message)
      this.inputMessage = ''
      this.adjustTextareaHeight()

      // 触发发送事件，由父组件负责设置加载状态
      this.$emit('send-message', message)
    },

    /**
     * 添加消息到聊天记录
     */
    addMessage(type, content) {
      this.messages.push({
        type,
        content,
        timestamp: new Date()
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    /**
     * 添加AI消息（支持流式更新）
     */
    addAIMessage(content, isComplete = false) {
      const lastMessage = this.messages[this.messages.length - 1]

      if (lastMessage && lastMessage.type === 'ai' && !lastMessage.isComplete) {
        // 累积更新最后一条AI消息内容
        lastMessage.content += content
        lastMessage.isComplete = isComplete
      } else {
        // 添加新的AI消息
        this.messages.push({
          type: 'ai',
          content,
          timestamp: new Date(),
          isComplete
        })
      }

      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    /**
     * 开始新的AI消息
     */
    startNewAIMessage() {
      this.messages.push({
        type: 'ai',
        content: '',
        timestamp: new Date(),
        isComplete: false
      })
    },

    /**
     * 完成当前AI消息
     */
    completeCurrentAIMessage() {
      const lastMessage = this.messages[this.messages.length - 1]
      if (lastMessage && lastMessage.type === 'ai') {
        lastMessage.isComplete = true
      }
    },

    /**
     * 设置加载状态
     */
    setLoading(loading) {
      this.isLoading = loading
    },

    /**
     * 设置正在输入状态
     */
    setTyping(typing) {
      this.isTyping = typing
    },

    /**
     * 滚动到底部
     */
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },

    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    /**
     * 自动调整输入框高度
     */
    adjustTextareaHeight() {
      const textarea = this.$refs.messageInput
      if (textarea) {
        textarea.style.height = 'auto'
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px'
      }
    },

    /**
     * 清空聊天记录
     */
    clearMessages() {
      this.messages = []
    }
  },
  mounted() {
    // 聚焦输入框
    this.$refs.messageInput?.focus()
  }
}
</script>

<style scoped>
.chat-room {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  text-align: center;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.chat-header h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  font-weight: 600;
}

.chat-id {
  font-size: 14px;
  opacity: 0.9;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f8f9fa;
}

.message {
  margin-bottom: 20px;
  display: flex;
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message.ai .message-content {
  background: white;
  color: #333;
  border: 1px solid #e1e5e9;
  border-bottom-left-radius: 4px;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
}

.message-text {
  line-height: 1.5;
  word-wrap: break-word;
  white-space: pre-wrap;
}

.message-time {
  font-size: 12px;
  margin-top: 8px;
  opacity: 0.7;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-input {
  background: white;
  padding: 20px;
  border-top: 1px solid #e1e5e9;
  box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
}

.input-container {
  display: flex;
  gap: 12px;
  align-items: flex-end;
  max-width: 1200px;
  margin: 0 auto;
}

.input-container textarea {
  flex: 1;
  border: 2px solid #e1e5e9;
  border-radius: 20px;
  padding: 12px 16px;
  font-size: 16px;
  resize: none;
  outline: none;
  transition: border-color 0.3s ease;
  font-family: inherit;
  line-height: 1.5;
  min-height: 44px;
  max-height: 120px;
}

.input-container textarea:focus {
  border-color: #667eea;
}

.input-container textarea:disabled {
  background-color: #f8f9fa;
  cursor: not-allowed;
}

.send-button {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 20px;
  padding: 12px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-height: 44px;
}

.send-button:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-button:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    padding: 15px;
  }

  .chat-header h2 {
    font-size: 20px;
  }

  .chat-messages {
    padding: 15px;
  }

  .message-content {
    max-width: 85%;
  }

  .chat-input {
    padding: 15px;
  }

  .input-container {
    gap: 8px;
  }

  .send-button {
    padding: 12px 16px;
    font-size: 14px;
  }
}
</style>
